import cv2
from imutils import contours
import numpy as np
import argparse
import matplotlib.pyplot as plt


def sort_contours(cnts, method="left-to-right"):
    reverse = False
    i = 0

    if method == "right-to-left" or method == "bottom-to-top":
        reverse = True

    if method == "top-to-bottom" or method == "bottom-to-top":
        i = 1
    boundingBoxes = [cv2.boundingRect(c) for c in cnts] #用一个最小的矩形，把找到的形状包起来x,y,h,w
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))

    return cnts, boundingBoxes



def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]
    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))
    resized = cv2.resize(image, dim, interpolation=inter)
    return resized


image_path='images/credit_card_01.png'
template_path='images/ocr_a_reference.png'


# 读取一个模板图像
img = cv2.imread(template_path)
plt.imshow(img[:,:,[2,1,0]])


# 转换为灰度图
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(ref,cmap=plt.cm.gray)


# 转换为二值图像
ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
plt.imshow(ref,cmap=plt.cm.gray)


# 计算轮廓
#cv2.findContours()函数接受的参数为二值图，即黑白的（不是灰度图）,cv2.RETR_EXTERNAL只检测外轮廓，cv2.CHAIN_APPROX_SIMPLE只保留终点坐标
#返回的list中每个元素都是图像中的一个轮廓
refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,refCnts,-1,(0,0,255),1) 
plt.imshow(img[:,:,[2,1,0]])


# 10个轮廓，第一个轮廓有30个点
print('len(refCnts):{}'.format(len(refCnts)))
print('refCnts[0].shape:{}'.format(refCnts[0].shape))


# 每个轮廓画出外接矩形,根据外接矩形左上顶点x值进行排序
refCnts =sort_contours(refCnts, method="left-to-right")[0] #排序，从左到右，从上到下
digits = {}

# 遍历每一个轮廓
for (i, c) in enumerate(refCnts):
	# 计算外接矩形并且resize成合适大小
	(x, y, w, h) = cv2.boundingRect(c)
	roi = ref[y:y + h, x:x + w]
	roi = cv2.resize(roi, (57, 88))

	# 每一个数字对应每一个模板
	digits[i] = roi


# 初始化卷积核
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))


#读取输入图像，预处理
image = cv2.imread(image_path)
plt.imshow(image[:,:,[2,1,0]])


image = resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
plt.imshow(gray,plt.cm.gray)


#礼帽操作，突出更明亮的区域  不懂？
tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel) 
plt.imshow(tophat,plt.cm.gray) 


gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)#ksize=-1相当于用3*3的
gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")
print (np.array(gradX).shape)
plt.imshow(gradX,cmap=plt.cm.gray)


#通过闭操作（先膨胀，再腐蚀）将数字连在一起
gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel) 
plt.imshow(gradX,cmap=plt.cm.gray)


#THRESH_OTSU会自动寻找合适的阈值，适合双峰，需把阈值参数设置为0
thresh = cv2.threshold(gradX, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] 
plt.imshow(thresh,cmap=plt.cm.gray)


#再来一个闭操作
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel) #再来一个闭操作
plt.imshow(thresh,cmap=plt.cm.gray)


# 计算轮廓
threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = threshCnts
cur_img = image.copy()
cv2.drawContours(cur_img,cnts,-1,(0,0,255),3) 
plt.imshow(cur_img[:,:,[2,1,0]])


locs = []

# 遍历轮廓
for (i, c) in enumerate(cnts):
	# 计算矩形
	(x, y, w, h) = cv2.boundingRect(c)
	ar = w / float(h)

	# 选择合适的区域，根据实际任务来，这里的基本都是四个数字一组
	if ar > 2.5 and ar < 4.0:
		if (w > 40 and w < 55) and (h > 10 and h < 20):
			#符合的留下来
			locs.append((x, y, w, h))

# 将符合的轮廓从左到右排序
locs = sorted(locs, key=lambda x:x[0])
locs


# 取出第一个轮廓
gX, gY, gW, gH = locs[0]
group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
plt.imshow(group,cmap=plt.cm.gray)


# 预处理 双峰阈值
group = cv2.threshold(group, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
plt.imshow(group,cmap=plt.cm.gray)


# 计算所有数字的轮廓
digitCnts,hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
digitCnts = contours.sort_contours(digitCnts,method="left-to-right")[0]


# 识别第一个数字
# 找到当前数值的轮廓，resize成合适的的大小
(x, y, w, h) = cv2.boundingRect(digitCnts[0])
roi = group[y:y + h, x:x + w]
roi = cv2.resize(roi, (57, 88))
plt.imshow(roi,cmap=plt.cm.gray)


# 计算匹配得分
scores = []

# 在模板中计算每一个得分
for (digit, digitROI) in digits.items():
    # 模板匹配
    result = cv2.matchTemplate(roi, digitROI,cv2.TM_CCOEFF)
    (_, score, _, _) = cv2.minMaxLoc(result)
    scores.append(score)

# 得到最合适的数字
np.argmax(scores)
